package com.daisuxia.back.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.utils.DwzResult;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.web.common.reslult.JsonResult;
import com.daisuxia.web.controller.BaseController;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.ObtainUserShortMessage;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.pojo.UserContacts;
import com.daisuxia.web.pojo.UserInfoImage;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IObtainUserShortMessageService;
import com.daisuxia.web.service.IUserBankService;
import com.daisuxia.web.service.IUserContactsService;
import com.daisuxia.web.service.IUserInfoImageService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.PageConfig;

@Controller
@RequestMapping("userManage/")
public class UserManageController extends BaseController{
	private static Logger logger = LoggerFactory.getLogger(BorrowOrderController.class);
	@Autowired
	public IUserService userService;
	@Autowired
	public IUserBankService userBankService;
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IUserInfoImageService userInfoImageService;
	@Autowired
	private IUserContactsService userContactsService;
	@Autowired
	private IObtainUserShortMessageService userShortMessageService;
	
	/**
	 * 用户管理 --》用户列表 
	 */
	@RequestMapping("gotoUserManage")
	public String gotoUserManage(HttpServletRequest request,HttpServletResponse response,Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			PageConfig<User> page = this.userService.getUserPage(params);
			model.addAttribute("pm", page);
			model.addAttribute("searchParams", params);//用于搜索框保留值

		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return "userInfo/userManageList";//用户列表jsp
	}
	
	/**
	 * 用户管理 --》用户列表 --》 操作
	 */
	@RequestMapping("operation")
	public void operation(HttpServletRequest request,HttpServletResponse response,Model model) {
		boolean bool = false;
		try {
			String id=request.getParameter("id");
			if(request.getParameter("option").equals("1")){//黑名单
				User user=new User();
				user.setId(id);
				user.setStatus("2");//2黑名单
				int count=this.userService.updateByPrimaryKeyUser(user);
				if(count>0){
					bool=true;
				}
			}else if(request.getParameter("option").equals("2")){//注销/删除资料账户
				User usr=this.userService.searchByUserid(Integer.parseInt(id));
				if(!StringUtils.isBlank(usr.getUserName())){
					usr.setUserName(usr.getUserName()+"*");
				} 
				if(!StringUtils.isBlank(usr.getIdNumber())){
					usr.setIdNumber(usr.getIdNumber()+"*");
				} 
				if(!StringUtils.isBlank(usr.getUserPhone())){
					usr.setUserPhone(usr.getUserPhone()+"*");
				} 
				usr.setStatus("3");//3 删除
				int count=this.userService.updateByPrimaryKeyUser(usr);
				if(count>0){
					bool=true;
				}
			}else if(request.getParameter("option").equals("3")){//保存修改手机号码
				User user=new User();
				user.setId(id);
				user.setUserName(request.getParameter("userPhone"));//用户名称
				user.setUserPhone(request.getParameter("userPhone"));//用户手机号码
				int count=this.userService.updateByPrimaryKeyUser(user);
				if(count>0){
					bool=true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		SpringUtils.renderDwzResult(response, bool, bool ? "操作成功" : "操作失败", DwzResult.CALLBACK_CLOSECURRENT);
	}
	
	/**
	 * 新旧号码更改
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("userManagePhone")
	public String userManagePhone (HttpServletRequest request,HttpServletResponse response,Model model){
		Map<String, String> params =this.getParameters(request);
		User user=this.userService.searchByUserid(Integer.parseInt(params.get("id")));
		model.addAttribute("id",user.getId());
		model.addAttribute("userPhone",user.getUserPhone());
		return "userInfo/userManageUpdatePhone";
	}
	
	/**
	 * 用户通讯录  
	 */
	@RequestMapping("gotoUserContacts")
	public String gotoUserContacts(HttpServletRequest request,HttpServletResponse response,Model model){
		HashMap<String, Object> params =this.getParametersO(request);
		PageConfig<UserContacts> contacts=this.userContactsService.selectUserContactsList(params);
		model.addAttribute("pm", contacts);
		model.addAttribute("searchParams", params);//用于搜索框保留值
		
		return "userInfo/userManagePhone";
	}
	
	/**
	 * 用户短信列表  
	 */
	@RequestMapping("gotoUserShortMsg")
	public String gotoUserShortMsg(HttpServletRequest request,HttpServletResponse response,Model model){
		HashMap<String, Object> params =this.getParametersO(request);
		PageConfig<ObtainUserShortMessage> contacts=this.userShortMessageService.selectUserShortMsgList(params);
		model.addAttribute("pm", contacts);
		model.addAttribute("searchParams", params);//用于搜索框保留值
		
		return "userInfo/userManageShortMsg";
	}
	
	
	/**
	 * 用户详情
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("userdetails")
	public String userdetails (HttpServletRequest request,HttpServletResponse response,Model model){
		Map<String, String> params =this.getParameters(request);
		User user= userService.searchByUserid(Integer.parseInt(params.get("id")));
		String cardNo=user.getIdNumber();
		if(cardNo!=null&&cardNo.length()>=18){
			String yy= cardNo.substring(6,10); //出生的年份
			String mm= cardNo.substring(10,12); //出生的月份
			String dd = cardNo.substring(12,14); //出生的日期 
			String birthday = yy.concat("-").concat(mm).concat("-").concat(dd);
			model.addAttribute("birthday",birthday);
			model.addAttribute("age", SpringUtils.calculateAge(birthday,"yy-MM-dd"));

		}
		user.setEducation(User.EDUCATION_TYPE.get(user.getEducation()));
		user.setPresentPeriod(User.RESIDENCE_DATE.get(user.getPresentPeriod()));
		user.setMaritalStatus(User.MARRIAGE_STATUS.get(user.getMaritalStatus()));
		user.setFristContactRelation(User.CONTACTS_FAMILY.get(user.getFristContactRelation()));
		user.setSecondContactRelation(User.CONTACTS_OTHER.get(user.getSecondContactRelation()));
		model.addAttribute("user",user);
		model.addAttribute("borrow", borrowOrderService.selectBorrowOrderUseId(Integer.parseInt(params.get("id"))));
		UserCardInfo info=userService.findUserBankCard(Integer.parseInt(params.get("id")));
		model.addAttribute("bankCard",info);
		List<UserInfoImage> userInfoImage=this.userInfoImageService.selectImageByUserId(Integer.parseInt(params.get("id")));
		model.addAttribute("InfoImage", userInfoImage);
		HashMap<String, Object> paramsM = new HashMap<String, Object>();
		paramsM.put("userId",user.getId());
		paramsM.put("statusList", new int[]{20,21,22,23,30,-20,-11});
		PageConfig<BorrowOrder> userBorrows = borrowOrderService.findPage(paramsM);
		model.addAttribute("userBorrows", userBorrows);
		model.addAttribute("params", params);
		return "userInfo/userdetails";
	}
	
	@RequestMapping("updadteBankCard")
	public String updadteBankCard(HttpServletRequest request,HttpServletResponse response,Model model){
		Map<String, String> params =this.getParameters(request);
		UserCardInfo info=userService.findUserBankCard(Integer.parseInt(params.get("id")));
		model.addAttribute("bankIndo", info);
		List<Map<String,Object>> mapList=userBankService.findAllBankInfo();
		model.addAttribute("bankList", mapList);
		model.addAttribute("params", params);
		return "userInfo/updadteBankCard";
	}
	
	/**
	 * 重新绑定银行卡
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("updateBankCard")
	public void updateBankCard(HttpServletRequest request,HttpServletResponse response,Model model){
		boolean bool=false;
		JsonResult result=null;
		try{
				Map<String,String> pams=this.getParameters(request); 
				result=userBankService.updateUpserBankCard(pams);
				if(result.isSuccessed()){
					bool=true;
				}
		}catch (Exception e) {
			result=new JsonResult("500","系统异常请稍后重试");
			e.printStackTrace();
		}finally{
			SpringUtils.renderDwzResult(response, bool, bool ? "操作成功": result.getMsg(), DwzResult.CALLBACK_CLOSECURRENT);
		}
	}
	
	public int calculateAge(String birthday,String format){
		int age=0;
		try {
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			Date today = sdf.parse(birthday);
			age=date.getYear()-today.getYear();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return age;
	}
	
	/**
	 * 银行卡列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("userBankCardList")
	public String userBankCardList(HttpServletRequest request,HttpServletResponse response, Model model){
		try{
			HashMap<String, Object> params = getParametersO(request);
			model.addAttribute("params", params);// 用于搜索框保留值
			PageConfig<Map<String,String>> pageConfig=userBankService.findAllUserBankCardList(params);
			model.addAttribute("pm", pageConfig);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "userInfo/userBankCardList";
	}
	/**
	 * 实名认证列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("userRealNameList")
	public String userRealNameList(HttpServletRequest request,HttpServletResponse response, Model model){
		try{
			HashMap<String, Object> params = getParametersO(request);
			model.addAttribute("params", params);// 用于搜索框保留值
			PageConfig<Map<String,String>> pageConfig=userService.realNmaeList(params);
			model.addAttribute("pm", pageConfig);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "userInfo/userRealNameList";
	}
	/**
	 * 用户认证列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("userCertificationList")
	public String userCertificationList(HttpServletRequest request,HttpServletResponse response, Model model){
		try{
			HashMap<String, Object> params = getParametersO(request);
			model.addAttribute("params", params);// 用于搜索框保留值
			PageConfig<Map<String,String>> pageConfig=userService.certificationList(params);
			model.addAttribute("pm", pageConfig);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "userInfo/userCertificationList";
	}
	/**
	 *用户通讯录列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("addressBookList")
	public String addressBookList(HttpServletRequest request,HttpServletResponse response, Model model){
		try{
			HashMap<String, Object> params = getParametersO(request);
			model.addAttribute("params", params);// 用于搜索框保留值
			PageConfig<UserContacts> pageConfig=userContactsService.selectUserContactsList(params);
			model.addAttribute("pm", pageConfig);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "userInfo/addressBookList";
	}
}
